import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import Layout from '@/views/layout/index.vue'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useTagsViewStore } from '../store/tagsView'
NProgress.configure({ 
  showSpinner: false,
  speed: 300 
})
// 基础路由
const constantRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        name: 'Index',
        component: () => import('@/views/Index.vue'),
        meta: { 
          title: '首页-智慧教培 教育平台系统', 
          hidden: true 
        }
      },
      {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/ExamLogin.vue'),
        meta: { 
          title: '登录页-智慧教培 教育平台系统', 
          hidden: true 
        }
      },
      {
        path: '/personalcenter',
        name: 'PersonalCenter',
        component: () => import('@/views/PersonalCenter.vue'),
        meta: { 
          title: '个人中心-智慧教培 教育平台系统', 
          hidden: true 
        }
      },
      {
        path: '/notice',
        name: 'AnnouncementList',
        component: () => import('@/views/AnnouncementList.vue'),
        meta: { 
          title: '公告中心-智慧教培 教育平台系统', 
          hidden: true 
        }
      },
      { 
        path: '/notice/detail/:id', 
        component: () => import('@/views/AnnouncementDetail.vue'),
         meta: { 
          title: '公告详情-智慧教培 教育平台系统', 
          hidden: true 
        }
        },
        {
          path: '/rules',
          name: 'Rules',
          component: () => import('@/views/Rules.vue'),
          meta: { 
            title: '考试规范-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
        {
          path: '/about', 
          name: 'About',
          component: () => import('@/views/About.vue'),
           meta: { 
            title: '关于我们-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
        {
          path: '/privacy', 
          name: 'Privacy',
          component: () => import('@/views/Privacy.vue'),
           meta: { 
            title: '隐私政策-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
        {
          path: '/faq', 
          name: 'Faq',
          component: () => import('@/views/Faq.vue'),
           meta: { 
            title: '常见问题-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
        {
          path: '/terms', 
          name: 'Terms',
          component: () => import('@/views/Terms.vue'),
           meta: { 
            title: '服务条款-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
        {
          path: '/payResult',
          name: 'PayResult',
          component: () => import('@/views/PayResult.vue'),
           meta: { 
            title: '支付结果-智慧教培 教育平台系统', 
            hidden: true 
          }
        },
]

// 异步路由（根据权限动态加载）
export const asyncRoutes: RouteRecordRaw[] = [
  {
    path: '/home',
    name: 'Home',
    redirect: '/home/dashboard',
    component: Layout,
    meta: { 
      title: '首页', 
      icon: 'House',
      roles: ['admin'] 
    },
    children: [
      {
        path: '/home/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/system/home/Dashboard.vue'),
        meta: { 
          hidden:true,
          title: '工作台', 
          icon: 'PieChart',
          roles: ['admin'] 
        }
      }
    ]
  },

  {
    path: '/base',
    component: Layout,
    meta: { title: '基础数据管理', icon: 'Grid' },
    children: [
      {
        path: '/base/alipay',
        component: () => import('@/views/alipay/Index.vue'),
        meta: { 
          title: '支付宝支付管理', 
          icon: 'Document',
          roles: ['admin']
        }
      },
      {
        path: '/base/notice',
        component: () => import('@/views/notice/NoticeList.vue'),
        meta: { 
          title: '公告管理', 
          icon: 'Document',
          roles: ['admin']
        }
      },
    ]
  },
  {
    path: '/system',
    component: Layout,
    meta: { title: '系统管理', icon: 'Setting' },
    redirect: '/system/user',
    children: [
      {
        path: '/system/user',// 使用绝对路径
        component: () => import('@/views/system/user/UserList.vue'),
        meta: { 
          title: '用户管理', 
          icon: 'User',
          roles: ['admin'] 
        }
      },
      {
        path: '/system/role',// 使用绝对路径
        component: () => import('@/views/system/role/RoleList.vue'),
        meta: { 
          title: '角色管理', 
          icon: 'Avatar',
          roles: ['admin']
        }
      }
    ]
  },
  // 404必须放在最后
  { 
    path: '/:pathMatch(.*)*', 
    component: () => import('@/views/404.vue'),
    meta: { hidden: true }
  }
]

// 先创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes:constantRoutes
})

// 白名单
const whiteList = ['/login', '/401','/404','/','/notice']
// 是否已添加动态路由标记
let isAddDynamicRoutes = false
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const userStore = useUserStore()
  
  // 已登录状态
  if (userStore.token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 检查用户信息是否已加载
      if (!userStore.roles.length||!isAddDynamicRoutes) {
        try {
          
          // 获取用户信息
          await userStore.getUserInfo()
          const permissionStore = usePermissionStore()
          
 
          // 根据角色生成动态路由
          if (!isAddDynamicRoutes) {
        
            const accessRoutes = await permissionStore.generateRoutes(userStore.roles)
            accessRoutes.forEach(route => router.addRoute(route))
            isAddDynamicRoutes = true
            // 重定向到原始目标路由
            next({ ...to, replace: true })
            return
          }
          next()
        } catch (error) {
          // 获取用户信息失败时重置令牌
          userStore.resetToken()
          ElMessage.error(error || '权限验证失败')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } 
  // 未登录状态
  else {
    const isWhiteListed = whiteList.some(path => to.path === path || to.path.startsWith(path + '/'))
    if (isWhiteListed) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to) => {
  NProgress.done()
  // 从最深层的子路由开始向上查找 meta.title
  const nearestRouteWithTitle = to.matched.slice().reverse().find(route => route.meta?.title)

  // 设置标题，若未找到则使用默认标题
  document.title = nearestRouteWithTitle?.meta.title || '智慧教培 教育平台系统'
  // 添加标签
  const tagsViewStore = useTagsViewStore()
  // 不添加白名单路由
  if (whiteList.includes(to.path)) return

  // 隐藏的菜单不添加到标签页
  if(!to.meta?.hidden){
    tagsViewStore.addView(to)
  }
  
  // 保持最多10个标签
  if (tagsViewStore.visitedViews.length > 10) {
    tagsViewStore.delView(tagsViewStore.visitedViews[0])
  }
})
export default router
